<template>
  <div class="page-container">
    <!--面包屑导航-->
    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>营销中心</el-breadcrumb-item>
        <el-breadcrumb-item>其他类促销</el-breadcrumb-item>
        <el-breadcrumb-item> 换购</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!--搜索条件+操作按钮栏-->
    <div class="toolbar">
      <el-form
        :inline="true"
        :model="filters"
        :size="size"
        ref="filters"
        :rules="filtersRules"
      >
        <el-row class="search-input">
          <el-form-item prop="promName" label="活动名称：">
            <el-input
              v-model="filters.promName"
              placeholder="活动名称"
              clearable
              maxlength="80"
            ></el-input>
          </el-form-item>
          <el-form-item prop="promotionCode" label="活动ID：">
            <el-input
              v-model="filters.promotionCode"
              placeholder="活动ID"
              maxlength="80"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item prop="frontPromType" label="活动类型：">
            <el-select v-model="filters.frontPromType" placeholder="全部" clearable>
              <el-option
                v-for="item in frontPromTypes"
                :key="item.type"
                :label="item.name"
                :value="item.type"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="creatorNameForSearch" label="创建人：">
            <el-input
              v-model="filters.creatorNameForSearch"
              placeholder="创建人"
              clearable
              maxlength="80"
            ></el-input>
          </el-form-item>
          <el-form-item label="渠道：" prop="channelId">
            <el-select v-model="filters.channelId" placeholder="全部" clearable>
              <el-option
                v-for="item in channelOption"
                :key="item.id"
                :label="item.channelName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item prop="activityType">
          <el-select v-model="filters.activityType" placeholder="参与方式">
                <el-option
                v-for="item in activityTypes"
                :key="item.activityType"
                :label="item.label"
                :value="item.activityType">
                </el-option>
            </el-select>
          </el-form-item>-->
          <el-form-item prop="merchantId" v-if="false">
            <el-select
              v-model="filters.merchantId"
              placeholder="活动商家："
              @change="changeMerchant"
              clearable
            >
              <el-option
                v-for="item in merchantIds"
                :key="item.merchantId"
                :label="item.label"
                :value="item.merchantId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="storeId" v-if="false">
            <el-select v-model="filters.storeId" placeholder="活动店铺：" clearable>
              <el-option
                v-for="item in storeIds"
                :key="item.storeId"
                :label="item.label"
                :value="item.storeId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-row class="times">
            <el-form-item label="活动时间：" prop="startTime">
              <el-date-picker
                v-model="filters.startTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
                placeholder="开始时间"
                class="input_postion w211"
                clearable
                @change="changeStartDate"
                :picker-options="startDateDisabled"
              ></el-date-picker>
            </el-form-item>
            <span class="times-to">-</span>
            <el-form-item prop="endTime">
              <el-date-picker
                v-model="filters.endTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
                placeholder="结束时间"
                class="input_postion w211"
                clearable
                @change="changeEndDate"
                :picker-options="endDateDisabled"
              ></el-date-picker>
            </el-form-item>
          </el-row>
        </el-row>
        <!--操作按钮-->
        <el-row class="search-button">
          <!--重置-->
          <el-form-item>
            <kt-button 
              :label="$t('action.reset')"
               class="resetButton"
               icon="el-icon-refresh"
              @click="resetForm('filters')"
              :plain="true"
            />
          </el-form-item>
          <!--查询-->
          <el-form-item>
            <kt-button
              icon="el-icon-search"
              :label="'搜索'"
              @click="getPromotionList()"
               class="searchButton"
            />
          </el-form-item>
          
          <!--创建活动-->
          <el-form-item>
            <kt-button
              label="创建活动"
              @click="createPage()"
              class="searchButton"
              perms="market:increase:add"
            />
          </el-form-item>
          <!--通过模板添加活动-->
          <el-form-item>
            <kt-button
              label="通过模板添加活动"
              @click="useTemp()"
              class="searchButton"
              perms="market:increase:temp"
            />
          </el-form-item>
        </el-row>
      </el-form>
    </div>

    <!--标签页栏-->
    <div class="tab-container">
      <el-tabs v-model="activeName">
        <el-tab-pane
          v-for="item in tabMapOptions"
          :key="item.key"
          :label="item.label"
          :name="item.key"
        >
          <tab-pane
            v-if="activeName == item.key"
            :type="item.key"
            ref="child"
            :parentFilters="filters"
            v-on:SecondSell="SecondSell"
          />
        </el-tab-pane>
      </el-tabs>
    </div>

    <!--通过模板添加活动按钮弹出框-->
    <el-dialog
      :title="'选择模板'"
      :visible.sync="useTempDialogVisible"
      :close-on-click-modal="false"
    >
      <div>
        <div class="flex">
          <el-form :inline="true" :model="dataForm" :size="size" ref="dataForm" :rules="dataFormRules">
            <!--搜索输入框-->
              <el-form-item label="活动类型：" class="w178">
                <el-select v-model="dataForm.promType" disabled clearable>
                  <el-option label="换购促销" :value="Number(8)"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item prop="templateName" label="模板名称： " class="w178">
                <el-input v-model="dataForm.templateName" clearable maxlength="80" placeholder="模板名称"></el-input>
              </el-form-item>
          </el-form>
          <el-row class="t_r mb30">
            <kt-button
              icon="el-icon-search"
              :label="'搜索'"
              @click="tempPageQuery"
              class="searchButton"
            />
          </el-row>
        </div>
        <div >
          <div class="tab-container">
            <el-table
              :data="tableData"
              :header-cell-style="{
                color: '#FFF',
                'background-color': '#409EFF',
                'text-align': 'center'
              }"
              :highlight-current-row="true"
              :max-height="1500"
              :size="size"
              align="center"
            >
              <el-table-column prop="id" label="ID" align="center">
              </el-table-column>
              <el-table-column align="center" prop="promType" label="活动类型">
                <template slot-scope="scope">
                  <span v-if="scope.row.promType == 1">单一促销</span>
                  <span v-else-if="scope.row.promType == 2">满量促销</span>
                  <span v-else-if="scope.row.promType == 3">满额促销</span>
                  <span v-else-if="scope.row.promType == 4">秒杀</span>
                  <span v-else-if="scope.row.promType == 5">赠送类促销</span>
                  <span v-else-if="scope.row.promType == 6">组合促销</span>
                  <span v-else-if="scope.row.promType == 7">单品X件优惠</span>
                  <span v-else-if="scope.row.promType == 8">换购</span>
                  <span v-else-if="scope.row.promType == 9">预售</span>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                prop="templateName"
                label="模板名称"
              >
              </el-table-column>
              <el-table-column align="center" prop="creatorName" label="创建人：">
              </el-table-column>
              <el-table-column
                align="center"
                prop="createTime"
                label="创建时间"
              >
              </el-table-column>
              <el-table-column
                align="center"
                fixed="right"
                label="操作"
              >
                <template slot-scope="scope">
                  <el-button
                    @click="used(scope.row)"
                    type="text"
                    class="textButton"
                    size="small"
                    >使用</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <el-row class="t_r">
              <el-pagination
                v-if="tableData.length == 0"
                layout="total, sizes, prev, pager, next, jumper"
                @current-change="handleCurrentChangeForTemplate"
                :current-page="dataForm.limit"
                :page-size="dataForm.start"
                :total="templateTableDataSize"
                :page-sizes="[10, 20, 30, 40]"
                @size-change="handleSizeChangeForTemplate"
              ></el-pagination>
              </el-row>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import marketRequest from "@/market/request/marketRequest";
import {
  front_prom_types,
  chanel_codes,
  prom_types
} from "@/market/dict/marketDict";
import KtButton from "@/views/Core/KtButton";
import { format } from "@/utils/datetime";
import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";
import { darkmagenta } from "color-name";
import tabPane from "./components/TabPaneIncrease";
export default {
  name: "Tab",
  components: {
    tabPane,
    KtButton,
    TableColumnFilterDialog
  },
  data() {
    var checkStartTime = (rule, value, callback) => {
      if (value == null || typeof value == "undefined") {
        callback();
      }
      if (
        this.filters.endTime == null ||
        typeof this.filters.endTime == "undefined"
      ) {
        callback();
      }
      if (
        new Date(value).getTime() > new Date(this.filters.endTime).getTime()
      ) {
        callback(new Error("开始时间不能大于结束时间"));
      }
      this.$refs.filters.clearValidate("endTime");
      callback();
    };
    var checkEndTime = (rule, value, callback) => {
      if (value == null || typeof value == "undefined") {
        callback();
      }
      if (
        this.filters.startTime == null ||
        typeof this.filters.startTime == "undefined"
      ) {
        callback();
      }
      if (
        new Date(value).getTime() < new Date(this.filters.startTime).getTime()
      ) {
        callback(new Error("结束时间不能小于开始时间"));
      }
      this.$refs.filters.clearValidate("startTime");
      callback();
    };
    var checkId = (rule, value, callback) => {
      if (value == null || typeof value == "undefined" || value == "") {
        callback();
      }
      var reg = /^[1-9]\d*$/;
      if (!reg.test(value)) {
        callback(new Error("请输入数字"));
      }
      callback();
    };
    return {
      channelOption:[],
      dataFormRules:{
        //templateName: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
      },
      filtersRules: {
        // promName: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
        // creatorNameForSearch: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
        //id: [{ validator: checkId, trigger: "change" }],
        startTime: [{ validator: checkStartTime, trigger: "change" }],
        endTime: [{ validator: checkEndTime, trigger: "change" }]
      },
      tableData: [],
      templateTableDataSize: 0,
      dataForm: {
        id: null,
        promType: 8, //换购
        templateName: null,
        limit: 10,
        start: 1
      },
      useTempDialogVisible: false,
      flag: false,
      form: {
        region: ""
      },
      option1: 1,
      option1: 2,
      option1: 3,
      tabMapOptions: [
        { label: "全部", key: "-1" },
        { label: "进行中", key: "5" },
        { label: "已结束", key: "8" },
        { label: "已过期", key: "6" },
        { label: "已关闭", key: "7" },
        { label: "未开始", key: "3" },
        { label: "待提交", key: "1" },
        { label: "待审核", key: "2" },
        { label: "审核未通过", key: "4" },
        { label: "活动草稿", key: "9" },
        
        //{ label: "审核通过", key: "11" },
      ],
      activeName: "-1",
      createdTimes: 0,
      size: "small",
      filters: {
        promName: null,
        promotionCode: null,
        id: "",
        promType: 8,
        channelCode: "",
        activityType: "",
        merchantId: "",
        creatorNameForSearch: null,
        startTime: "",
        endTime: "",
        storeId: "",
        type: "",
        frontPromType: "",
        t: "sysConfig",
        queryname: "",
        promotionCode:'',
      },
      frontPromTypes: this.getFrntPromType(),
      promTypes: 5,
      channelCodes: chanel_codes,
      activityTypes: [
        { activityType: "", label: "请选择" },
        { activityType: "0", label: "自建" },
        { activityType: "1", label: "报名" }
      ],
      merchantIds: [{ merchantId: null, label: "请选择" }],
      storeIds: [{ storeId: null, label: "请选择" }],
      startDateDisabled: {},//开始时间限制
      endDateDisabled: {},//结束时间限制
    };
  },
  methods: {
    queryChannelListOther: function() {
      var this_ = this;
      this.utils.request.queryChannelListOther({}, function(res) {
        if (res.code == "0000") {
          this_.channelOption = res.data;
        }
      });
    },
    changeStartDate: function() {
      var this_ = this;
      this_.endDateDisabled = {
        disabledDate: time => {
          if (this_.filters.startTime) {
            return time.getTime() <= new Date(this_.filters.startTime).getTime();
          }
        }
      };
    },
    changeEndDate: function() {
      var this_ = this;
      this_.startDateDisabled = {
        disabledDate: time => {
          if (this_.filters.endTime) {
            return time.getTime() >= new Date(this_.filters.endTime).getTime();
          }
        }
      };
    },
    handleSizeChangeForTemplate(pageNum) {
      this.dataForm.limit = pageNum;
      this.tempPageQuery();
    },
    handleCurrentChangeForTemplate(pageSize) {
      this.dataForm.limit = 1;
      this.dataForm.start = pageSize;
      this.tempPageQuery();
    },
    // 使用模板
    useTemp() {
      this.tableData = [];
      this.useTempDialogVisible = true;
      this.tempPageQuery();
    },
    // 使用模板，使用的时候先复制再跳转
    used(row) {
      let callback = res => {
        if (res.code == "0000") {
          this.$router.push(`/increasePromotionCreate?id=${res.data}&auth=0&active=1`);
        } else {
          this.$message({ message: "使用模板失败", type: "fail" });
        }
      };
      let parm = {};
      parm.id = row.promotionId;
      marketRequest.promotionDeepCopy(parm, callback);
    },
    // 分页查询
    tempPageQuery() {
      let callback = res => {
        if (res.code == "0000") {
          this.templateTableDataSize = res.data.total;
          this.tableData = res.data.rows;
        } else {
          this.$message({ message: "查询失败", type: "fail" });
        }
      };
      this.utils.request.templatePageQuery(this.dataForm, callback);
    },
    getFrntPromType: function(row, column, cellValue, index) {
      return front_prom_types.filter(e => {
        return e.code == "increase_front_prom_type";
      });
    },
    // 时间格式化
    dateFormat: function(row, column, cellValue, index) {
      return format(row[column.property]);
    },

    resetForm(formName) {
      //需要校验的keys
			let keys = ["endTime","startTime","creatorNameForSearch","frontPromType","promotionCode","promName","channelId"]
			//调用校验
			let  boo = this.seachTableUtils.checkFromIsNull(this.filters,keys)
			if(!boo){
				return;
      }

      if (this.$refs[formName] != undefined) {
        this.$refs[formName].resetFields();
      }
      this.$refs.child[0].listQuery.pageNo = 1;
      this.$refs.child[0].getList();
    },
    createPage() {
      //this.$router.push("/CreateHandsel" + "?auth=0");
      this.$router.push("/IncreasePromotionCreate" + "?auth=1&active=1");
      // this.$router.push("/CreatePromotion"+"?auth=1");
    },
    getPromotionList() {
      this.$refs.child[0].listQuery.pageNo = 1;
      this.$refs.child[0].getList();
    },
    changeMerchant() {
      let this_ = this;
      this.utils.request.queryStoreList(
        { start: 1, limit: 10000000, merchantId: this.filters.merchantId },
        function(res) {
          if (res.code == "0000") {
            res.data.rows.forEach(item => {
              //,{'storeId':'0','label':'张小二bbc店铺'},{'storeId':'1','label':'张小二的京东店'}
              let store = {};
              store.storeId = item.id;
              store.label = item.storeName;
              this_.storeIds.push(store);
            });
          }
        }
      );
    },
    SecondSell() {
      this.flag = true;
    }
  },
  watch: {
    activeName(val) {
      this.$router.push(`${this.$route.path}?tab=${val}`);
    }
  },
  created() {
    //获取商家列表
    let this_ = this;
    this.utils.request.queryMerchantList(
      { start: 1, limit: 10000000 },
      function(res) {
        if (res.code == "0000") {
          res.data.rows.forEach(item => {
            let merchant = {};
            merchant.merchantId = item.id;
            merchant.label = item.name;
            this_.merchantIds.push(merchant);
          });
        }
      }
    );
    this.changeMerchant();
    // init the default selected tab
    //this.frontPromTypes = front_prom_types;
    const tab = this.$route.query.tab;
    if (tab) {
      this.activeName = tab;
    }
  },
  mounted() {this.queryChannelListOther()}
};
</script>

<style scoped lang="scss">
.page-container {
  // padding: 22px 40px 188px;
  overflow: hidden;

  // .toolbar {
  //   float: left;
  //   padding-top: 10px;
  //   margin-bottom: 48px;
  //   width: 100%;
  //   border-bottom: 1px solid #dbdbdb;
  //   // /deep/ .input_postion {
  //   //   margin-right: 0;
  //   //   /deep/ .el-date-editor {
  //   //     width: 180px;
  //   //   }
  //   // }
  //   .buttons {
  //     text-align: right;
  //     margin: 64px 0 30px 0;
  //   }
  // }
  .reset {
    background-color: #fff;
    color: #409eff;
  }
  // .el-dialog {
  //   /deep/ .el-dialog__header {
  //     padding-top: 54px;
  //     padding-bottom: 47px;
  //     /deep/ .el-dialog__title {
  //       font-size: 28px;
  //       color: #333333;
  //       font-weight: 700 !important;
  //     }
  //     /deep/ .el-dialog__close {
  //       font-size: 20px;
  //     }
  //   }
  //   /deep/ .el-dialog__body {
  //     .el-form {
  //       /deep/ .el-form-item__label {
  //         color: #999999;
  //         font-size: 18px;
  //       }
  //     }
  //   }
  // }
}

/deep/ .el-tabs--card>.el-tabs__header .el-tabs__item:first-child{
  border-left: 1px solid #9B9DA3 !important;
  &.is-active {
    border-color: #0090FF !important;
  }
}
.search-input{
  .times{
    .w211{
      width: 211px !important;
      /deep/ .el-input__inner{
        width: 211px !important;
      }
    }
  }
}
</style>
